package com.connect.ftp.access;

import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPSClient;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

public class FileTransferImp implements FileTransfer {
	private String hostname;
	private int port;
	private String user;
	private String passwd;
	private String remotePath;
	private String localPath;
	
	public FileTransferImp(String hostname, String user, String passwd, String remotePath, String localPath, String sport){
		this.hostname = hostname;
		this.port = Integer.parseInt(sport);
		this.user = user;
		this.passwd = passwd;
		this.remotePath = remotePath;
		this.localPath = localPath;
	}
	
	@Override
	public void download() throws IOException {
		// file name
		String fileName = getFileName();
		JSch jsch = new JSch();
        Session session = null;
        try {
            session = jsch.getSession(user, hostname, port);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword(passwd);
            session.connect();
            String localFile=localPath+fileName;
            String remoteFile=remotePath+fileName;
            Channel channel = session.openChannel("sftp");
            channel.connect();
            ChannelSftp sftpChannel = (ChannelSftp) channel;
            sftpChannel.get(remoteFile, localFile);
            sftpChannel.exit();
            session.disconnect();
        } catch (JSchException e) {
            e.printStackTrace();  
        } catch (SftpException e) {
            e.printStackTrace();
        }
		//download
		/*
		FTPSClient ftpClient = new FTPSClient(false); 
		ftpClient.connect(hostname,port);
		ftpClient.login(user, passwd);
		ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
		
		String localFile=localPath+fileName;
		FileOutputStream fos = new FileOutputStream(localFile);  
		
		String remoteFile=remotePath+fileName;
        ftpClient.retrieveFile(remoteFile, fos);
        ftpClient.disconnect();
        */
	}
	
	private String getFileName(){
		DateFormat dateFormat = new SimpleDateFormat("yyMMdd");
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DATE, -1);
		return "verify.log."+dateFormat.format(cal.getTime());
	}
}
